﻿// <copyright file="WebAnalyticsEvents.cs" company="Microsoft Corporation">
// Copyright (c) 2009 Microsoft Corporation All Rights Reserved
// </copyright>
// <author>Michael S. Scherotter</author>
// <email>mischero@microsoft.com</email>
// <date>2009-10-16</date>
// <summary>WebAnalyticsEvents class</summary>

namespace Microsoft.WebAnalytics
{
    using System;
    using System.ComponentModel.Composition;

    /// <summary>
    /// Web Analytics events that dispatchers hook into
    /// </summary>
    [Export]
    public class WebAnalyticsEvents
    {
        #region Constructors

        /// <summary>
        /// Initializes a new instance of the WebAnalyticsEvents class.  This is typically created by MEF.
        /// </summary>
        public WebAnalyticsEvents()
        {
            System.Diagnostics.Debug.WriteLine("WebAnalyticsEvents constructor");
        }
        #endregion

        #region Events
        /// <summary>
        /// The Track Event handler
        /// </summary>
        public event EventHandler<AnalyticsEventArgs> TrackEvent;

        #endregion

        #region Methods

        /// <summary>
        /// Dispatch events
        /// </summary>
        /// <param name="analyticsEvent">the event to dispatch to the attached services</param>
        /// <param name="fromCache">true if this event was from the cache or false if it an immediate event</param>
        /// <returns>true if the events were hooked up and dispatched</returns>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We don't want exceptions in the analytics services to crash the app.")]
        internal bool DispatchEvents(AnalyticsEvent analyticsEvent, bool fromCache)
        {
            if (this.TrackEvent == null)
            {
                System.Diagnostics.Debug.WriteLine("Caching {0} event because no trackers are connected yet.", analyticsEvent.Name);

                return false;
            }

            var args = new AnalyticsEventArgs(analyticsEvent, fromCache);

            try
            {
                this.TrackEvent(this, args);
            }
            catch (System.Exception se)
            {
                System.Diagnostics.Debug.WriteLine("Error dispatching event to subscriber(s): {0}", se.Message);
            }

            return true;
        }
        #endregion
    }
}
